<template>
  <div class="settings-container">
    <n-scrollbar class="settings-scrollbar">
      <div class="settings-content">
        <!-- 用户信息设置 -->
        <div class="settings-section">
          <h2 class="section-title">
            <n-icon size="20" class="section-icon">
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
                <path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/>
              </svg>
            </n-icon>
            用户信息
          </h2>
          <div class="section-content">
            <div class="user-info-display">
              <div class="current-user">
                <span class="user-label">当前用户：</span>
                <span class="username">{{ currentUsername }}</span>
              </div>
              <n-button type="primary" size="small" class="change-password-btn" @click="changePassword">
                修改密码
              </n-button>
            </div>
          </div>
        </div>

        <!-- 分割线 -->
        <n-divider />
        
        <!-- 主题设置 -->
        <div class="settings-section">
          <h2 class="section-title">
            <n-icon size="20" class="section-icon">
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
                <path d="M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12s4.477 10 10 10zm0-2V4a8 8 0 1 1 0 16z"/>
              </svg>
            </n-icon>
            主题与外观
          </h2>
          <div class="section-content">
            <n-form-item label="主题模式" class="setting-item">
              <n-select
                v-model:value="formValue.theme"
                :options="themeOptions"
                placeholder="选择主题"
                style="width: 300px;"
              />
            </n-form-item>
            <n-form-item label="自动保存会话" class="setting-item">
              <n-switch v-model:value="formValue.autoSave" />
            </n-form-item>
          </div>
        </div>

        <!-- 分割线 -->
        <n-divider />
        
        <!-- AI模型设置 -->
        <div class="settings-section">
          <h2 class="section-title">
            <n-icon size="20" class="section-icon">
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
                <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"/>
              </svg>
            </n-icon>
            AI模型设置
          </h2>
          <div class="section-content">
            <n-form-item label="默认对话模型" class="setting-item">
              <ModelSelector 
                :current-model="modelStore.currentChatModel" 
                model-tag="对话"
                @select-model="updateDefaultChatModel" 
              />
            </n-form-item>
            <n-form-item label="默认向量模型" class="setting-item">
              <n-select
                v-model:value="formValue.vectorModel"
                :options="vectorModelOptions"
                placeholder="选择默认向量模型"
                style="width: 300px;"
                :loading="loadingModels"
              />
            </n-form-item>
          </div>
        </div>

        <!-- 分割线 -->
        <n-divider />
        
        <!-- 网络与连接 -->
        <div class="settings-section">
          <h2 class="section-title">
            <n-icon size="20" class="section-icon">
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
                <path d="M20.5 3l-.16.03L15 5.1 9 3 3.36 4.9c-.21.07-.36.25-.36.48V20.5c0 .28.22.5.5.5l.16-.03L9 18.9l6 2.1 5.64-1.9c.21-.07.36-.25.36-.48V3.5c0-.28-.22-.5-.5-.5zM15 19l-6-2.11V5l6 2.11V19z"/>
              </svg>
            </n-icon>
            网络与连接
          </h2>
          <div class="section-content">
            <n-form-item label="后端服务地址" class="setting-item">
              <n-input 
                v-model:value="formValue.apiBaseUrl" 
                placeholder="输入后端服务地址，如：http://127.0.0.1:8080" 
                style="width: 300px;" 
              />
            </n-form-item>
            <n-form-item label="启用网络搜索" class="setting-item">
              <n-switch v-model:value="settingsStore.networkingEnabled" @update:value="updateNetworkingEnabled" />
            </n-form-item>
            <n-form-item label="启用MCP工具" class="setting-item">
              <n-switch v-model:value="settingsStore.mcpEnabled" @update:value="updateMcpEnabled" />
            </n-form-item>
          </div>
        </div>

        <!-- 分割线 -->
        <n-divider />
        
        <!-- 工作目录与Git设置 -->
        <div class="settings-section">
          <h2 class="section-title">
            <n-icon size="20" class="section-icon">
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
                <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
              </svg>
            </n-icon>
            工作目录与Git设置
          </h2>
          <div class="section-content">
            <n-form-item label="工作目录" class="setting-item">
              <n-input 
                v-model:value="formValue.workDirectory" 
                placeholder="选择您的工作目录，用于存储创作内容" 
                style="width: 300px;" 
                readonly
              />
              <n-button type="primary" size="small" style="margin-left: 8px;" @click="selectWorkDirectory">
                浏览
              </n-button>
            </n-form-item>
            
            <n-form-item label="Git软件目录" class="setting-item">
              <n-input 
                v-model:value="formValue.gitExecutablePath" 
                placeholder="Git软件安装目录，如 C:\Program Files\Git\bin\git.exe" 
                style="width: 300px;" 
                readonly
              />
              <n-button type="primary" size="small" style="margin-left: 8px;" @click="selectGitExecutable">
                浏览
              </n-button>
            </n-form-item>
            
            <n-form-item label="Git自动提交" class="setting-item">
              <n-switch v-model:value="formValue.gitAutoCommit" />
              <span style="margin-left: 8px; color: var(--text-secondary);">启用后，系统将自动保存您的创作内容到Git仓库</span>
            </n-form-item>
            
            <n-form-item label="自动提交间隔" class="setting-item" v-if="formValue.gitAutoCommit">
              <n-input-number 
                v-model:value="formValue.gitAutoCommitInterval" 
                :min="1" 
                :max="60" 
                style="width: 120px;" 
              />
              <span style="margin-left: 8px; color: var(--text-secondary);">分钟</span>
            </n-form-item>
            
            <n-form-item label="Git历史显示方式" class="setting-item">
              <n-select
                v-model:value="formValue.gitShowHistoryInGraph"
                :options="gitHistoryDisplayOptions"
                style="width: 200px;"
              />
            </n-form-item>
            
            <n-form-item label="差异显示样式" class="setting-item">
              <n-select
                v-model:value="formValue.gitDiffDisplayStyle"
                :options="gitDiffStyleOptions"
                style="width: 200px;"
              />
            </n-form-item>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="settings-actions">
          <n-flex gap="16" justify="center">
            <n-button type="primary" @click="saveAllSettings" size="large">
              保存所有设置
            </n-button>
            <n-button @click="resetAllSettings" size="large">
              重置为默认值
            </n-button>
          </n-flex>
        </div>
      </div>
    </n-scrollbar>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { NFormItem, NInput, NSelect, NSwitch, NButton, NFlex, NIcon, NDivider, NScrollbar, useMessage } from 'naive-ui'
import { useUserStore } from '../../auth/stores/user'
import { useModelStore } from '../../shared/stores/model'
import { useSettingsStore } from '../../shared/stores/settings'
import ModelSelector from '../../chat/components/ModelSelector.vue'


const userStore = useUserStore()
const modelStore = useModelStore()
const settingsStore = useSettingsStore()
const loadingModels = ref(false)
const message = useMessage()

// 计算当前用户名，优先从userStore获取用户信息，其次从localStorage获取
const currentUsername = computed(() => {
  // 优先从userStore获取用户信息
  if (userStore.userInfo && userStore.userInfo.nickname) {
    return userStore.userInfo.nickname
  }
  
  // 其次从localStorage获取完整的用户信息
  const userInfoStr = localStorage.getItem('user_info')
  if (userInfoStr) {
    try {
      const userInfo = JSON.parse(userInfoStr)
      // 优先使用nickname，其次使用username
      return userInfo.nickname || userInfo.username || ''
    } catch {
      // JSON解析失败，继续其他方式
    }
  }
  
  // 最后从userStore.userId获取
  return userStore.userId || '未登录'
})

// 表单数据 - 使用多个Store的状态管理
const formValue = ref({
  username: localStorage.getItem('username') || currentUsername.value || '',
  theme: settingsStore.theme || 'light',
  autoSave: settingsStore.autoSave !== false, // 默认为true
  vectorModel: Number(modelStore.vectorModel) || 0, // 改为number类型，默认为0
  
  // API设置
  apiBaseUrl: settingsStore.apiBaseUrl || 'http://127.0.0.1:8080',
  
  // 工作目录和Git设置
  workDirectory: settingsStore.workDirectory || 'C:\\Users\\User\\AppData\\Local\\novel',
  gitExecutablePath: settingsStore.gitExecutablePath || 'C:\\Program Files\\Git\\bin\\git.exe',
  gitAutoCommit: settingsStore.gitAutoCommit !== false, // 默认为true
  gitAutoCommitInterval: settingsStore.gitAutoCommitInterval || 5,
  gitShowHistoryInGraph: settingsStore.gitShowHistoryInGraph !== false ? 'true' : 'false', // 默认为'true'
  gitDiffDisplayStyle: settingsStore.gitDiffDisplayStyle || 'side-by-side'
})

// 主题选项
const themeOptions = [
  { label: '浅色', value: 'light' },
  { label: '深色', value: 'dark' },
  { label: '自动', value: 'auto' }
]

// Git历史显示选项
const gitHistoryDisplayOptions = [
  { label: '图形显示', value: 'true', type: 'ignored' as const },
  { label: '列表显示', value: 'false', type: 'ignored' as const }
]

// Git差异显示样式选项
const gitDiffStyleOptions = [
  { label: '并排显示', value: 'side-by-side' },
  { label: '内联显示', value: 'inline' }
]

// 对话模型选项
const chatModelOptions = ref<Array<{label: string, value: number, name: string}>>([])

// 向量模型选项
const vectorModelOptions = ref<Array<{label: string, value: number}>>([])

// 加载AI模型列表
async function loadAiModels() {
  loadingModels.value = true
  try {
    // 使用 useAuthManager 的缓存机制
    const { getAuthManager } = await import("../../auth/composables/useAuthManager");
    const authManager = getAuthManager()
    const isAuthenticated = await authManager.checkAuthStatus()
    
    if (!isAuthenticated) {
      console.log('用户未登录，显示登录弹窗');
      // 使用authPromptService显示登录弹窗
      try {
        const { authPromptService } = await import("../../auth/services/auth-prompt-service")
        await authPromptService.showLoginPrompt()
      } catch (error) {
        console.error('显示登录弹窗失败:', error)
      }
      return
    }
    
    // 确保模型列表已加载
    await modelStore.loadModels()
    
    // 过滤出对话类型的模型
    const chatModels = modelStore.getModelsByTag('chat')
    chatModelOptions.value = chatModels.map((model: any) => ({
      label: model.name,
      value: Number(model.id), // 确保模型ID是number类型
      // 保存模型名称用于显示
      name: model.name
    }))
    
    // 过滤出向量(嵌入)类型的模型
    const vectorModels = modelStore.getModelsByTag('嵌入')
    vectorModelOptions.value = vectorModels.map((model: any) => ({
      label: model.name,
      value: Number(model.id) // 确保模型ID是number类型
    }))
  } catch (error) {
    console.error('加载AI模型失败:', error);
  } finally {
    loadingModels.value = false
  }
}

// 更新默认对话模型
function updateDefaultChatModel(modelId: string | number) {
  // 确保modelId是number类型，与后端保持一致
  const modelIdNum = Number(modelId)
  modelStore.setCurrentChatModel(modelIdNum)
  
  // 同时更新对话标签的模型
  modelStore.setModelByTag('对话', modelIdNum)
  
  // 更新currentModelId为number类型
  modelStore.setCurrentModelId(modelIdNum)
  
  // 获取模型信息并更新标签，使用number类型的modelId
  const selectedModel = modelStore.getModelById(modelIdNum)
  if (selectedModel && selectedModel.tags) {
    modelStore.setCurrentModelTags(selectedModel.tags)
  }
}

// 选择工作目录
const selectWorkDirectory = async () => {
  try {
    // 检查是否在Electron环境中
    if (window.electronAPI) {
      const result = await (window.electronAPI as any).selectDirectory()
      if (result && !result.canceled) {
        formValue.value.workDirectory = result.filePaths[0]
      }
    } else {
      // 非Electron环境的模拟实现
      const path = prompt('请输入工作目录路径:')
      if (path) {
        formValue.value.workDirectory = path
      }
    }
  } catch (error) {
    console.error('选择工作目录失败:', error);
    message.error('选择工作目录失败: ' + (error instanceof Error ? error.message : '未知错误'))
  }
}

// 选择Git可执行文件
const selectGitExecutable = async () => {
  try {
    // 检查是否在Electron环境中
    if (window.electronAPI) {
      const result = await (window.electronAPI as any).selectFile({
        filters: [
          { name: '可执行文件', extensions: ['exe'] }
        ]
      })
      if (result && !result.canceled) {
        formValue.value.gitExecutablePath = result.filePaths[0]
      }
    } else {
      // 非Electron环境的模拟实现
      const path = prompt('请输入Git可执行文件路径:')
      if (path) {
        formValue.value.gitExecutablePath = path
      }
    }
  } catch (error) {
    console.error('选择Git可执行文件失败:', error);
    message.error('选择Git可执行文件失败: ' + (error instanceof Error ? error.message : '未知错误'))
  }
}

// 保存所有设置
async function saveAllSettings() {
  try {
    // 保存用户名到localStorage，但不设置userId
    if (formValue.value.username) {
      localStorage.setItem('username', formValue.value.username)
    }
    
    // 保存主题设置
    settingsStore.setTheme(formValue.value.theme)
    
    // 保存自动保存设置
    settingsStore.setAutoSave(formValue.value.autoSave)
    
    // 保存向量模型设置
    modelStore.setVectorModel(formValue.value.vectorModel)
    
    // 保存API设置
    settingsStore.setApiBaseUrl(formValue.value.apiBaseUrl)
    
    // 保存工作目录和Git设置
    settingsStore.setWorkDirectory(formValue.value.workDirectory)
    settingsStore.setGitExecutablePath(formValue.value.gitExecutablePath)
    settingsStore.setGitAutoCommit(formValue.value.gitAutoCommit)
    settingsStore.setGitAutoCommitInterval(formValue.value.gitAutoCommitInterval)
    settingsStore.setGitShowHistoryInGraph(formValue.value.gitShowHistoryInGraph === 'true')
    settingsStore.setGitDiffDisplayStyle(formValue.value.gitDiffDisplayStyle)
    
    // 准备用户自定义配置数据
    const customConfig = {
      embeddingModelId: Number(formValue.value.vectorModel),
      embeddingModelName: vectorModelOptions.value.find(opt => opt.value === formValue.value.vectorModel)?.label || '',
      chatModelId: Number(modelStore.currentChatModel),
      chatModelName: chatModelOptions.value.find(opt => opt.value === modelStore.currentChatModel)?.label || '',
      theme: formValue.value.theme,
      enableMemory: settingsStore.memoryEnabled,
      enableNetworking: settingsStore.networkingEnabled,
      enableMcp: settingsStore.mcpEnabled,
      autoSave: formValue.value.autoSave,
      apiBaseUrl: formValue.value.apiBaseUrl,
      workDirectory: formValue.value.workDirectory,
      gitExecutablePath: formValue.value.gitExecutablePath,
      gitAutoCommit: formValue.value.gitAutoCommit,
      gitAutoCommitInterval: formValue.value.gitAutoCommitInterval,
      gitShowHistoryInGraph: formValue.value.gitShowHistoryInGraph,
      gitDiffDisplayStyle: formValue.value.gitDiffDisplayStyle
    }
    
    // 调用API保存用户配置到后端
    const { authService } = await import("../../auth/services/auth-service");
    const response = await authService.updateUserCustomConfig(customConfig)
    
    if (response.code === 0) {
      console.log('所有设置已保存:', formValue.value);
      // 添加成功提示
      message.success('设置保存成功')
    } else {
      console.error('保存用户配置失败:', response.msg);
      // 添加错误提示
      message.error('保存失败: ' + response.msg)
    }
  } catch (error) {
    console.error('保存设置时出错:', error);
    // 添加错误提示
    message.error('保存设置时出错: ' + (error instanceof Error ? error.message : '未知错误'))
  }
}

// 重置所有设置为默认值
function resetAllSettings() {
  const defaultUsername = currentUsername.value || '用户'
  const defaultWorkDirectory = 'C:\\Users\\User\\AppData\\Local\\novel'
  
  formValue.value = {
    username: defaultUsername,
    theme: 'light',
    autoSave: true,
    vectorModel: 0,
    apiBaseUrl: 'http://127.0.0.1:8080',
    workDirectory: defaultWorkDirectory,
    gitExecutablePath: 'C:\\Program Files\\Git\\bin\\git.exe',
    gitAutoCommit: true,
    gitAutoCommitInterval: 5,
    gitShowHistoryInGraph: 'true',
    gitDiffDisplayStyle: 'side-by-side'
  }
  
  // 清除本地存储的设置
  localStorage.removeItem('username')
  
  // 重置用户存储的设置
  userStore.setUserId(0)
  settingsStore.setTheme('light')
  settingsStore.setAutoSave(true)
  modelStore.setVectorModel(0)
  settingsStore.setMemoryEnabled(false)
  settingsStore.setNetworkingEnabled(false)
  settingsStore.setMcpEnabled(false)
  settingsStore.setApiBaseUrl('http://127.0.0.1:8080')
  
  // 重置工作目录和Git设置
  settingsStore.setWorkDirectory(defaultWorkDirectory)
  settingsStore.setGitExecutablePath('C:\\Program Files\\Git\\bin\\git.exe')
  settingsStore.setGitAutoCommit(true)
  settingsStore.setGitAutoCommitInterval(5)
  settingsStore.setGitShowHistoryInGraph(true)
  settingsStore.setGitDiffDisplayStyle('side-by-side')
  
  message.info('设置已重置为默认值')
}

// 修改密码
function changePassword() {
  // 实现修改密码功能
  message.info('修改密码功能待实现')
}

// 更新网络功能启用状态
function updateNetworkingEnabled(value: boolean) {
  settingsStore.setNetworkingEnabled(value)
}

// 更新MCP功能启用状态
function updateMcpEnabled(value: boolean) {
  settingsStore.setMcpEnabled(value)
}

// 组件挂载时加载模型列表
onMounted(() => {
  loadAiModels()
})
</script>

<style scoped>
.settings-container {
  padding: 24px;
  background: var(--bg-secondary);
  height: calc(100vh - 50px); /* 减去HeaderBar高度 */
  width: 100%;
  box-sizing: border-box;
}

.settings-scrollbar {
  height: 100%;
  width: 100%;
}

.settings-content {
  max-width: 800px;
  margin: 0 auto;
  background: var(--bg-card);
  border-radius: 8px;
  padding: 32px;
  box-shadow: 0 1px 3px var(--shadow-color);
}

/* n-scrollbar样式自定义 */
:deep(.n-scrollbar-rail) {
  background-color: var(--bg-secondary) !important;
}

:deep(.n-scrollbar-bar) {
  background-color: var(--border-color) !important;
  border-radius: 3px;
}

:deep(.n-scrollbar-bar:hover) {
  background-color: var(--text-secondary) !important;
}

.settings-section {
  margin-bottom: 0;
  padding: 0;
  background: transparent;
  border: none;
}

.section-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0 0 16px 0;
}

.section-icon {
  margin-right: 12px;
  color: var(--accent-color);
}

.section-content {
  padding-left: 0;
}

.setting-item {
  margin-bottom: 20px;
  padding: 0;
  background: transparent;
  border: none;
}

.setting-item:last-child {
  margin-bottom: 0;
}

.setting-actions {
  display: flex;
  gap: 12px;
  margin-top: 8px;
}

.user-info-display {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
}

.current-user {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.user-label {
  color: var(--text-secondary);
  margin-right: 8px;
}

.username {
  font-weight: 600;
  color: var(--text-primary);
}

.change-password-btn {
  margin-left: auto;
}

.settings-actions {
  margin-top: 32px;
  margin-bottom: 32px;
  padding-top: 24px;
  border-top: 1px solid var(--border-color);
  text-align: center;
}

/* 侧边栏菜单显示控制样式 */
.menu-visibility-controls {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 10px;
  margin-top: 4px;
}

.menu-control-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 6px 0;
}

.menu-label {
  font-size: 14px;
  color: var(--text-secondary);
  margin-right: 8px;
}

/* 分割线样式 */
:deep(.n-divider) {
  margin: 32px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .settings-container {
    padding: 16px;
  }
  
  .settings-content {
    padding: 24px 16px;
    border-radius: 0;
    margin: 0;
  }
  
  .section-title {
    font-size: 16px;
  }
  
  .setting-actions {
    flex-direction: column;
    gap: 8px;
  }
}

@media (max-width: 480px) {
  .settings-container {
    padding: 12px;
  }
  
  .settings-content {
    padding: 16px 12px;
  }
}
</style>